package com.erp.module.jingXiHua.jingXiHuaXiangXi

import android.app.Activity
import androidx.appcompat.app.AlertDialog
import android.content.Intent
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.AdapterView
import com.erp.Interface.OnUserDataInterface
import com.erp.R
import com.erp.activity.BaseActivity
import com.erp.activity.DanjianivActivity
import com.erp.activity.MainKActivity
import com.erp.bean.FileBean
import com.erp.bean.JingXiHuaBean
import com.erp.bean.PhotoBean
import com.erp.mclass.QuanXian
import com.erp.mclass.UnCeHandler
import com.erp.module.jingXiHua.FragmentJingXiHua
import com.erp.module.jingXiHua.JingXiHuaModel
import com.erp.module.zhiLiang.xingJianZhiLiang.IXJWuLiaoZhiLiangKp
import com.erp.myAdapter.ArrayAdapter
import com.erp.myAdapter.FileAdapter
import com.erp.myAdapter.PhotoAdapter
import com.erp.permission.PermissionListener
import com.erp.util.Dialogutil
import com.erp.util.JsonUtil
import com.erp.util.Myutil
import com.erp.util.PermissionUtils
import kotlinx.android.synthetic.main.activity_jingxihua.*
import kotlinx.android.synthetic.main.header_knoya.*
import org.json.JSONException
import org.json.JSONObject

/**
 * Created by Administrator on 2019/3/22/022.
 * 作者：刘洋
 */
class JingXiHuaActivity  : BaseActivity(), View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

    var updatedialog: AlertDialog? = null
    var md = JingXiHuaModel()
    lateinit var bean : JingXiHuaBean
    var ghid =FragmentJingXiHua.ghid
    var ghname =FragmentJingXiHua.ghname;
    lateinit var PhotoAdapter : PhotoAdapter
    lateinit var FileAdapter : FileAdapter
    lateinit var AuditNameAdapter : ArrayAdapter<String>
    lateinit var ApprovalNameAdapter : ArrayAdapter<String>
    lateinit var deletephoto : MutableList<PhotoBean>
    lateinit var deletefile : MutableList<FileBean>
    override fun getLayoutId(): Int {
        return R.layout.activity_jingxihua
    }

    override fun initCreate() {
        bean = FragmentJingXiHua.bean
        deletephoto = ArrayList()
        deletefile = ArrayList()
        Myutil.setet(bean.content_scheme,EtContentScheme)
        Myutil.setet(bean.file_category,EtFileCategory)
        Myutil.setet(bean.duty_department,EtDutyDepartment)
        Myutil.setet(bean.duty_name,EtDutyName)
        Myutil.settv(bean.approval_name,TvApprovalName)
        Myutil.settv(bean.audit_name, TvAuditName)
        Myutil.setet(bean.audit_defeated_reason,EtDefeatedAudit)
        Myutil.setet(bean.approval_defeated_reason,EtDefeatedapprova)
        if(bean.audit_status=="2"){
            LlApprovalName.visibility=View.GONE
        }else{
            LlApprovalName.visibility=View.VISIBLE
        }
        if(bean.audit_status=="0"&&bean.creator_uid== MainKActivity.uid) {
            AtAuditName.visibility=View.VISIBLE
            TvAuditName.visibility=View.GONE
        }else{
            AtAuditName.visibility=View.VISIBLE
            TvAuditName.visibility=View.GONE
        }
        if(bean.audit_status=="0"&&bean.audit_name== MainKActivity.name){
            AtApprovalName.visibility=View.VISIBLE
            TvApprovalName.visibility=View.GONE
        }else if(bean.audit_status=="1"){
            AtApprovalName.visibility=View.VISIBLE
            TvApprovalName.visibility=View.GONE
        }
        if(bean.audit_status=="0"||bean.audit_status=="2"){
            LlDefeatedAudit.visibility=View.VISIBLE
        }else{
            LlDefeatedAudit.visibility=View.GONE
        }
        if((bean.approval_status=="0"&&bean.audit_status=="1")||bean.approval_status=="2"){
            LlDefeatedapprova.visibility=View.VISIBLE
        }else{
            LlDefeatedapprova.visibility=View.GONE
        }
        gonghao()
        AuditNameAdapter = ArrayAdapter(this@JingXiHuaActivity, android.R.layout.simple_dropdown_item_1line, ghname)
        ApprovalNameAdapter = ArrayAdapter(this@JingXiHuaActivity, android.R.layout.simple_dropdown_item_1line, ghname)
        AtAuditName.setAdapter(AuditNameAdapter)
        AtApprovalName.setAdapter(ApprovalNameAdapter)
        AtAuditName.setOnClickListener { AtAuditName.showDropDown() }
        AtApprovalName.setOnClickListener { AtApprovalName.showDropDown() }
        iv_header_left.setOnClickListener(this)
        tv_header_right.setOnClickListener(this)
        BtAuditOk.setOnClickListener(this)
        BtAuditNot.setOnClickListener(this)
        BtApprovalOk.setOnClickListener(this)
        BtApprovalNot.setOnClickListener(this)
        BtAbolishAudit.setOnClickListener(this)
        BtAbolishApproval.setOnClickListener(this)
        tv_header_right.visibility=View.VISIBLE
        tv_header_right.text="保存"
        iv_header_left.visibility=View.VISIBLE
        if(bean.audit_status=="0"&&bean.audit_name== MainKActivity.name){
            BtAuditOk.visibility= View.VISIBLE
            BtAuditNot.visibility=View.VISIBLE
        }else{
            BtAuditOk.visibility= View.GONE
            BtAuditNot.visibility=View.GONE
        }
        if((bean.audit_status=="1"||bean.audit_status=="2")&&bean.approval_status=="0"&&bean.audit_name== MainKActivity.name){
            BtAbolishAudit.visibility=View.VISIBLE
        }else{
            BtAbolishAudit.visibility=View.GONE
        }
        if(bean.approval_status=="0"&&bean.audit_status=="1"&&bean.approval_name== MainKActivity.name){
            BtApprovalOk.visibility=View.VISIBLE
            BtApprovalNot.visibility=View.VISIBLE
        }else{
            BtApprovalOk.visibility=View.GONE
            BtApprovalNot.visibility=View.GONE
        }
        if((bean.approval_status=="1"||bean.approval_status=="2")&&bean.approval_name== MainKActivity.name){
            BtAbolishApproval.visibility=View.VISIBLE
        }else{
            BtAbolishApproval.visibility=View.GONE
        }
        Log.d("LS",bean.toString())
        mbean.listphoto=bean.listphoto
        mbean.listfile=bean.listfile
        PhotoAdapter = PhotoAdapter(this,mbean.listphoto,true)
        FileAdapter = FileAdapter(this,mbean.listfile,false)
        GvJingXiHuaPhoto.adapter=PhotoAdapter
        GvJingXiHuaFile.adapter=FileAdapter
        GvJingXiHuaPhoto.onItemClickListener = this
        GvJingXiHuaPhoto.onItemLongClickListener=this
        GvJingXiHuaFile.onItemLongClickListener=this
        GvJingXiHuaFile.onItemClickListener=this
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        UnCeHandler.buzhou="onActivityResult"
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                99 -> {
                    val selectedImage = data.data
                    val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
                    val c = contentResolver.query(selectedImage, filePathColumns, null, null, null)
                    c!!.moveToFirst()
                    val columnIndex = c.getColumnIndex(filePathColumns[0])
                    val imagePath = c.getString(columnIndex)
                    addphoto(imagePath)
                }
                100 -> {
                    val name = data.getStringExtra("dir")
                    addphoto(name)
                }
            }
        }
    }

    private fun addphoto(name: String) {
        UnCeHandler.buzhou="addphoto"
        val photo = PhotoBean()
        photo.uri = name
        mbean.listphoto.add(photo)
        PhotoAdapter.notifyDataSetChanged()
    }

    override fun onItemLongClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long): Boolean {
        when(parent){
            GvJingXiHuaPhoto -> {
                if(position<mbean.listphoto.size) {
                    val dialog = AlertDialog.Builder(this)
                    dialog.setTitle("提示")
                    dialog.setMessage("确定要删除这个照片")
                    dialog.setPositiveButton("确定") { dialog, which ->
                        deletephoto.add(mbean.listphoto[position])
                        mbean.listphoto.remove(mbean.listphoto[position])
                        PhotoAdapter.notifyDataSetChanged()
                    }
                    dialog.setNegativeButton("取消") { dialog, which -> dialog.dismiss() }
                    dialog.show()
                }
            }
            GvJingXiHuaFile -> {
                if(position<mbean.listfile.size) {
                    val dialog = AlertDialog.Builder(this)
                    dialog.setTitle("提示")
                    dialog.setMessage("确定要删除这个照片")
                    dialog.setPositiveButton("确定") { dialog, which ->
                        deletefile.add(mbean.listfile[position])
                        mbean.listfile.remove(mbean.listfile[position])
                        FileAdapter.notifyDataSetChanged()
                    }
                    dialog.setNegativeButton("取消") { dialog, which -> dialog.dismiss() }
                    dialog.show()
                }
            }
        }
        return true
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        when(parent){
            GvJingXiHuaFile -> {
                PermissionUtils.isupdate(this@JingXiHuaActivity, object : PermissionListener {
                    override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                        Dialogutil.downloaddialog1(mbean.listfile[position], this@JingXiHuaActivity)
                    }

                    override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                        Myutil.MyTost("没有权限，无法下载")
                    }
                })
            }
            GvJingXiHuaPhoto -> {
                if (position == bean.listphoto.size) {
                    Dialogutil.photodialog(this, null)
                } else {
                    val intent = Intent(this, DanjianivActivity::class.java)
                    intent.putExtra("url", bean.listphoto[position].uri)
                    startActivity(intent)
                }
            }
        }
    }

    var mbean = JingXiHuaBean()
    override fun onClick(v: View?) {
        mbean.id=bean.id
        when(v){
            iv_header_left->{
                finish()
            }
            BtAuditOk -> {
                mbean.audit_status="1"
                for (i in ghname.indices) {
                    if (ghname[i] == AtApprovalName.text.toString().trim { it <= ' ' }) {
                        mbean.approval_gonghao = ghid[i]
                    }
                }
                if(mbean.approval_gonghao==""||mbean.approval_gonghao=="0"){
                    Myutil.MyTost("审批人必须选择")
                    return
                }
                postJingXiHua()
            }
            BtAuditNot -> {
                mbean.audit_status="2"
                mbean.audit_defeated_reason=EtDefeatedAudit.text.toString()
                if(mbean.audit_defeated_reason==""){
                    Myutil.MyTost("审核退回原因必须填写")
                    return
                }
                postJingXiHua()
            }
            BtAbolishAudit -> {
                mbean.audit_status="-1"
                postJingXiHua()
            }
            BtApprovalOk -> {
                mbean.approval_status="1"
                postJingXiHua()
            }
            BtApprovalNot -> {
                mbean.approval_status="2"
                mbean.approval_defeated_reason=EtDefeatedapprova.text.toString()
                if(mbean.approval_defeated_reason==""){
                    Myutil.MyTost("审批退回原因必须填写")
                    return
                }
                postJingXiHua()
            }
            BtAbolishApproval -> {
                mbean.approval_status="-1"
                postJingXiHua()
            }
            iv_header_left->{
                finish()
            }
            tv_header_right -> {
                mbean.content_scheme=EtContentScheme.text.toString()
                mbean.file_category=EtFileCategory.text.toString()
                mbean.duty_department=EtDutyDepartment.text.toString()
                mbean.duty_name=EtDutyName.text.toString()
                mbean.guidance_name=EtGuidanceName.text.toString()
                mbean.approval_gonghao=bean.approval_gonghao
                mbean.audit_gonghao=bean.audit_gonghao
                if(ghname.size>0){
                    if(bean.audit_status=="0") {
                        for (i in ghname.indices) {
                            if (ghname[i] == AtAuditName.text.toString().trim { it <= ' ' }) {
                                mbean.audit_name = ghid[i]
                            }
                        }
                        if (mbean.audit_gonghao == "" || mbean.approval_gonghao == "0") {
                            Myutil.MyTost("审核人必须选择")
                            return
                        }
                    }
                    if(mbean.approval_status=="0"&&mbean.audit_status!="0") {
                        for (i in ghname.indices) {
                            if (ghname[i] == AtApprovalName.text.toString().trim { it <= ' ' }) {
                                mbean.approval_name = ghid[i]
                            }
                        }
                    }
                }
                postJingXiHua()
            }
        }
    }

    fun postJingXiHua(){
        if(QuanXian.isEditElaborateManagement){
            Myutil.MyTost("没有更改精细化的权限")
            return
        }
        updatedialog = Myutil.showupdatedialog(this, "正在上传", false)
        md.postJingXiHua(this,mbean,deletephoto,deletefile,object : OnUserDataInterface{
            override fun onUserData(data: String?) {
                Log.d("onUserData",data)
                updatedialog?.dismiss()
                try {
                    var jo = JSONObject(data)
                    bean.id=JsonUtil.getvolue(jo,"id")
                    bean.content_scheme=JsonUtil.getvolue(jo,"content_scheme")
                    bean.file_category=JsonUtil.getvolue(jo,"file_category")
                    bean.ctime=JsonUtil.getvolue(jo,"ctime")
                    bean.duty_department=JsonUtil.getvolue(jo,"duty_department")
                    bean.duty_name=JsonUtil.getvolue(jo,"duty_name")
                    bean.guidance_name=JsonUtil.getvolue(jo,"guidance_name")
                    bean.audit_name=JsonUtil.getvolue(jo,"audit_name")
                    bean.audit_time=JsonUtil.getvolue(jo,"audit_time")
                    bean.approval_name=JsonUtil.getvolue(jo,"approval_name")
                    bean.approval_time=JsonUtil.getvolue(jo,"approval_time")
                    bean.approval_status=JsonUtil.getvolue(jo,"approval_status")
                    bean.audit_status=JsonUtil.getvolue(jo,"audit_status")
                    bean.creator_uid=JsonUtil.getvolue(jo,"creator_uid")
                    bean.creator_uid=JsonUtil.getvolue(jo,"creator_uid")
                    bean.audit_defeated_reason=JsonUtil.getvolue(jo,"audit_defeated_reason")
                    bean.approval_defeated_reason=JsonUtil.getvolue(jo,"approval_defeated_reason")
                    bean.audit_gonghao=JsonUtil.getvolue(jo,"audit_gonghao")
                    bean.approval_gonghao=JsonUtil.getvolue(jo,"approval_gonghao")
                    var state = ""
                    if(bean.audit_status!="1"){
                        if(bean.audit_status=="0"){
                            state = "未审核";
                        }else if(bean.audit_status=="2"){
                            state = "审核未通过"
                        }
                    }else{
                        if(bean.approval_status=="0"){
                            state = "已审核未审批"
                        }else if(bean.approval_status=="2"){
                            state = "审批未通过"
                        }else if(bean.approval_status== "1"){
                            state = "已审批"
                        }
                    }
                    bean.listphoto.clear()
                    bean.listfile.clear()
                    var jsf = JsonUtil.getjsvolue(jo,"files")
                    for (j in 0 until jsf.length()) {
                        var jof = jsf.get(j) as JSONObject
                        var filemime = JsonUtil.getvolue(jof, "filemime")
                        if(filemime=="image/jpeg"){
                            var photo = PhotoBean()
                            photo.fid=JsonUtil.getvolue(jof,"fid")
                            photo.filename=JsonUtil.getvolue(jof,"filename")
                            photo.uri=JsonUtil.getvolue(jof,"uri")
                            bean.listphoto.add(photo)
                        }else{
                            var file = FileBean()
                            file.fid=JsonUtil.getvolue(jof,"fid")
                            file.filename=JsonUtil.getvolue(jof,"filename")
                            file.uri=JsonUtil.getvolue(jof,"uri")
                            file.filemime=filemime
                            bean.listfile.add(file)
                        }
                    }
                    bean.state=state
                }catch (e : JSONException){
                    e.printStackTrace()
                }
                initCreate()
            }

            override fun onNot(throwable: String?) {
                Log.d("onUserData",throwable)
                updatedialog?.dismiss()
            }

        })
    }


















    //获取工号数据
    fun gonghao(){
        if(ghid.size==0){
            getGongHaoLieBiao()
        }else{
            Log.d("TAAAG",bean.audit_gonghao)
            Log.d("TAAAG",ghid.toString())
            Log.d("TAAAG",ghname.toString())
            if (bean.audit_name != "") {
                for (i in ghid.indices) {
                    if (ghid[i] == bean.audit_gonghao) {
                        AtAuditName.setText(ghname[i])
                    }
                }
            }
            if (bean.approval_name != "") {
                for (i in ghid.indices) {
                    if (ghid[i] == bean.approval_gonghao) {
                        AtAuditName.setText(ghname[i])
                    }
                }
            }
        }
    }
    fun getGongHaoLieBiao() {
        if(IXJWuLiaoZhiLiangKp.gonghaos !=""){
            getgonghaojson(IXJWuLiaoZhiLiangKp.gonghaos)
            return
        }
        md.getZhiLiangGongHaoLieBiao(this, object : OnUserDataInterface {
            override fun onUserData(data: String) {
                Myutil.MyTost("获取工号列表")
                IXJWuLiaoZhiLiangKp.gonghaos = data
                getgonghaojson(data)
            }

            override fun onNot(throwable: String?) {
                Log.d("TAAAG", "throwable=" + Myutil.decodeUnicode(throwable))
            }

        })
    }
    fun getgonghaojson(data: String){
        UnCeHandler.buzhou="getgonghaojson"
        var gonghao: MutableList<String> = ArrayList()
        var gonghaoname: MutableList<String> = ArrayList()
        try {
            val jo = JSONObject(data)
            val keys = jo.keys()
            while (keys.hasNext()) {
                val key = keys.next() as String
                gonghao.add(key)
                gonghaoname.add(JsonUtil.getvolue(jo, key))
            }
            gonghao.removeAt(0)
            gonghaoname.removeAt(0)
            ghid.addAll(gonghao)
            ghname.addAll(gonghaoname)
            AuditNameAdapter.notifyDataSetChanged()
            ApprovalNameAdapter.notifyDataSetChanged()
            if (bean.audit_name != "") {
                for (i in ghid.indices) {
                    if (ghid[i] == bean.audit_gonghao) {
                        AtAuditName.setText(ghname[i])
                    }
                }
            }
            if (bean.approval_name != "") {
                for (i in ghid.indices) {
                    if (ghid[i] == bean.approval_gonghao) {
                        AtAuditName.setText(ghname[i])
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}